<template>
  <div class="fc-form-render">
    <el-form
      :model="model"
      v-bind="internalFormGlobalJson.props"
      :rules="internalFormGlobalJson.rules"
      :key="renderKey"
    >
      <RenderNode
        v-for="node in fields"
        :key="`${renderKey}-${node.id}`"
        :node="node"
        :model-value="model"
        @update:model-value="$emit('update:model', $event)"
      />
    </el-form>
  </div>
</template>

<script setup>
import { ref, onBeforeMount, onMounted,provide } from "vue";
import { useNodeIndex } from "./hooks/useNodeIndex.js";
import RenderNode from "./RenderNode.vue";
import Control from "./utils/control.js";

const formRenderControl=new Control()

// 注册中心控制器
provide('formRenderControl',formRenderControl)

const props = defineProps({
  config: {
    type: Object,
    required: true
  },
  model: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['update:model'])

// 使用节点索引 hooks
const {
  fields,
  indexStats,
  allNodes,
  rootNodes,
  leafNodes,
  buildNodeIndex,
  getNodeData,
  getNodesByLevel,
  getNodeInfo,
  getParentNode,
  getChildNodes,
  getSiblingNodes,
  getNodesByType,
  addNode,
  removeNode,
  updateNode,
  updateFields,
  hasNode
} = useNodeIndex(props.config.fields || [])

// 其他状态
const internalFormGlobalJson = ref({...props.config.formGlobalJson || {}})
const renderKey = ref(0)

// 手动重新加载
const reload = (conf) => {
  if (conf) {
    updateFields(conf.fields || [])
    internalFormGlobalJson.value = conf.formGlobalJson || {}
    renderKey.value += 1
    console.log('手动重新渲染已执行', conf)
  }
}

// 重置到初始配置
const reset = () => {
  updateFields([...props.config.fields || []])
  internalFormGlobalJson.value = {...props.config.formGlobalJson || {}}
  renderKey.value += 1
  console.log('重置到初始配置')
}

// 生命周期
onBeforeMount(() => {
  console.log('表单初始化前生命周期')
})

onMounted(() => {
  buildNodeIndex()
  console.log('表单初始化后生命周期，索引已构建', indexStats.value)
})

defineExpose({
  reload,
  reset,
  
  // 节点查找方法
  getNodeData,
  getNodeInfo,
  getParentNode,
  getChildNodes,
  getSiblingNodes,
  getNodesByType,
  getNodesByLevel,
  
  // 节点操作方法
  addNode,
  removeNode,
  updateNode,
  
  // 状态信息
  hasNode,
  indexStats,
  allNodes,
  rootNodes,
  leafNodes,
  
  // 索引管理
  buildNodeIndex
})
</script>
